package com.xckj.ibox.ui.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xckj.ibox.R;
import com.xckj.ibox.bean.HomeMenuBean;
import com.xckj.ibox.global.Constant;
import com.xckj.ibox.utils.LoadImageUtil;

import java.util.List;

/**
 * @Author: ChenYao
 * @Describe: 首页菜单
 * @Date: 2023/6/16 01:30
 */
public class HomeMenuAdapter extends RecyclerView.Adapter {
    private List<HomeMenuBean> homeMenuBeans;
    private OnItemClickListener onItemClickListener;

    @SuppressLint("NotifyDataSetChanged")
    public void setHomeMenuData(List<HomeMenuBean> homeMenuBeans) {
        this.homeMenuBeans = homeMenuBeans;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_menu, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
        itemViewHolder.itemView.setOnClickListener(view -> {
            if (null != onItemClickListener) {
                onItemClickListener.onItemClick(view, position);
            }
        });
        HomeMenuBean homeMenuBean = homeMenuBeans.get(position);
        LoadImageUtil.loadImage( homeMenuBean.image, itemViewHolder.ivIcon);
        itemViewHolder.tvTitle.setText(homeMenuBean.name);
    }

    @Override
    public int getItemCount() {
        return homeMenuBeans == null ? 0 : homeMenuBeans.size();
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {
        private final ImageView ivIcon;
        private final TextView tvTitle;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            ivIcon = itemView.findViewById(R.id.iv_icon);
            tvTitle = itemView.findViewById(R.id.tv_title);
        }
    }

    public interface OnItemClickListener {
        /**
         * Item子View的点击事件
         *
         * @param view     当前视图
         * @param position 当前索引
         */
        void onItemClick(View view, int position);
    }
}
